import { FC, ReactNode, useState } from "react";
import { CheckboxChangeEvent, CheckboxGroupProps } from "antd/es/checkbox";
import { get, isNil, map, omit } from "lodash";
import { Checkbox } from "antd";
import { CheckboxValueType } from "antd/es/checkbox/Group";

const CheckBoxGroup: FC<{
  value?: any[];
  onChange?: (v: any) => [];
  items: {
    key: string;
    label: string;
  }[];
  groupWrap?: (v: any) => ReactNode;
  itemWrap?: (v: any) => ReactNode;
}> = (props) => {
  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(false);
  // const checkBoxGroupProps: CheckboxGroupProps = omit(props, [
  //   "items",
  //   "itemWrap",
  //   "groupWrap",
  // ]);
  const itemWrap = props.itemWrap ?? ((v) => v);
  const groupWrap = props.groupWrap ?? ((v) => v);

  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    props.onChange?.(
      e.target.checked ? map(props.items, (item) => item.key) : []
    );
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };
  const onChange = (itemVal: CheckboxChangeEvent) => {
    // @ts-ignore
    let list = [...(props.value ?? [])];
    const { checked, value } = itemVal.target;
    if (checked) {
      list.push(value);
    } else {
      list = list.filter((val) => val !== value);
    }

    props.onChange?.(list);
    setIndeterminate(
      !!list.length && list.length < get(props.items, "length", 0)
    );
    setCheckAll(list.length === get(props.items, "length", 0));
  };
  return (
    <>
      {groupWrap(
        <>
          {itemWrap(
            <Checkbox
              indeterminate={indeterminate}
              checked={checkAll}
              onChange={onCheckAllChange}
            >
              全选
            </Checkbox>
          )}
          {map(props.items, ({ key, label }) =>
            itemWrap(
              <Checkbox
                value={key}
                onChange={onChange}
                checked={props.value?.includes(key)}
              >
                {label}
              </Checkbox>
            )
          )}
        </>
      )}
    </>
  );
};

export default CheckBoxGroup;
